package com.post799.soundapp;


import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;

import com.bappi.custom.activities.CustomTabActivity;
import com.bappi.utils.Constants;

public class TabsController extends CustomTabActivity {

	private static final String KEY_SHOW_HIDE_COMMAND = "SHOW_HIDE_COMMAND";
	private static final String KEY_TIME = "t";
	private static final String KEY_COMMAND = "c";
	private static final int COMMAND_TYPE_HIDE_BAR = 0;
	private static final int COMMAND_TYPE_SHOW_BAR = 1;
	private static final int COMMAND_TYPE_TOGGLE_BAR = 2;

	public static void showTabBar(SharedPreferences sp) {
		try {
			JSONObject jo = new JSONObject();
			jo.put(KEY_TIME, System.currentTimeMillis());
			jo.put(KEY_COMMAND, COMMAND_TYPE_SHOW_BAR);
			sp.edit().putString(KEY_SHOW_HIDE_COMMAND, jo.toString()).commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void hideTabBar(SharedPreferences sp) {
		try {
			JSONObject jo = new JSONObject();
			jo.put(KEY_TIME, System.currentTimeMillis());
			jo.put(KEY_COMMAND, COMMAND_TYPE_HIDE_BAR);
			sp.edit().putString(KEY_SHOW_HIDE_COMMAND, jo.toString()).commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void toggleTabBar(SharedPreferences sp) {
		try {
			JSONObject jo = new JSONObject();
			jo.put(KEY_TIME, System.currentTimeMillis());
			jo.put(KEY_COMMAND, COMMAND_TYPE_TOGGLE_BAR);
			sp.edit().putString(KEY_SHOW_HIDE_COMMAND, jo.toString()).commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static final String[] TABS = { "Tab1", "Tab2", "Tab3" };

	private TabHost tabs = null;
	private LinearLayout popupTabs;

	public void changeTab(int index) {
		tabs.setCurrentTab(index);
	}

	private SharedPreferences sharedPreferences;
	private OnSharedPreferenceChangeListener ospcl;


	@Override
	public void onCreate(Bundle icicle) {
		try {
			super.onCreate(icicle);
			setContentView(R.layout.tabs_controller);
			popupTabs = (LinearLayout) findViewById(R.id.popupTabs);

			String[] TAB_TITLES = { getString(R.string.text_tab1),
					getString(R.string.text_tab2),
					getString(R.string.text_tab3) };
			setDefaultTab(0);
			tabs = getTabHost();
			for (int i = 0; i < TABS.length; i++) {
				TabHost.TabSpec tab = tabs.newTabSpec(TABS[i]);

				ComponentName oneActivity = new ComponentName(getApplication()
						.getPackageName(), getApplication().getPackageName()
						+ "." + TABS[i]);

				tab.setContent(new Intent().setComponent(oneActivity));
				int id = R.drawable.custom_tab_1;
				switch (i) {
				case 0:
					id = R.drawable.custom_tab_1;
					break;
				case 1:
					id = R.drawable.custom_tab_2;
					break;
				case 2:
					id = R.drawable.custom_tab_3;
					break;
				}
				tab.setIndicator(new MyTabIndicator(this, id, TAB_TITLES[i]));
				tabs.addTab(tab);
			}
			sharedPreferences = PreferenceManager
					.getDefaultSharedPreferences(this);
			ospcl = new OnSharedPreferenceChangeListener() {

				public void onSharedPreferenceChanged(
						final SharedPreferences sp, String key) {
					try {
						
						if (KEY_SHOW_HIDE_COMMAND.equals(key)) {
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									try {
										String object = sp.getString(KEY_SHOW_HIDE_COMMAND, null);
										if(object!=null){
											JSONObject jo = new JSONObject(object);
											int command = jo.getInt(KEY_COMMAND);
											switch (command) {
											case COMMAND_TYPE_SHOW_BAR:
												popupTabs.setVisibility(View.VISIBLE);
												break;
											case COMMAND_TYPE_HIDE_BAR:
												popupTabs.setVisibility(View.GONE);
												break;
											case COMMAND_TYPE_TOGGLE_BAR:
												if (popupTabs.getVisibility() == View.GONE) {
													popupTabs.setVisibility(View.VISIBLE);
												} else {
													popupTabs.setVisibility(View.GONE);
												}
												break;
											default:
												break;
											}
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
								}
							});
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			sharedPreferences.registerOnSharedPreferenceChangeListener(ospcl);
			// tabs.getTabWidget().getChildTabViewAt(0).setEnabled(false);
			// tabs.getTabWidget().getChildTabViewAt(1).setEnabled(true);
			// tabs.getTabWidget().getChildTabViewAt(2).setEnabled(false);
			tabs.setCurrentTab(0);
			
			int startCount = sharedPreferences.getInt(Constants.KEY_APP_START_COUNTER, 0)+1;
			sharedPreferences.edit().putInt(Constants.KEY_APP_START_COUNTER, startCount).commit();
			if(!sharedPreferences.getBoolean(Constants.KEY_APP_RATED, false)){
				for(int i=0;i<Constants.RATING_POPUP_INDEXES.length;i++){
					if(Constants.RATING_POPUP_INDEXES[i] == startCount){
						showRatingPopup();
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	private void showRatingPopup() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setMessage(getString(R.string.rate_us))
				.setCancelable(false)
				.setPositiveButton(getString(R.string.ok),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								openMarket();
							}
						})
				.setNegativeButton(getString(R.string.later),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {

							}
						});
		final AlertDialog alert = builder.create();
		alert.show();
	}
	
	private void openMarket() {
		try {
			sharedPreferences.edit().putBoolean(Constants.KEY_APP_RATED, true).commit();
			String packageName = getApplication().getPackageName();
			Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(Uri.parse("market://details?id=" + packageName));
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

//	private void enableAllTabs() throws Exception {
//		tabs.getTabWidget().getChildTabViewAt(0).setEnabled(true);
//		tabs.getTabWidget().getChildTabViewAt(1).setEnabled(true);
//		tabs.getTabWidget().getChildTabViewAt(2).setEnabled(true);
//	}


	@Override
	protected void onDestroy() {
		try {
			if (sharedPreferences != null && ospcl != null) {
				sharedPreferences
						.unregisterOnSharedPreferenceChangeListener(ospcl);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	public static class MyTabIndicator extends LinearLayout {
		public MyTabIndicator(Context context, int iconId, String label) {
			super(context);
			View tab = LayoutInflater.from(context).inflate(
					R.layout.tab_indicator, this);
			ImageView iv = (ImageView) tab.findViewById(R.id.tab_image);
			iv.setImageResource(iconId);
			TextView tv = (TextView) tab.findViewById(R.id.tab_label);
			tv.setText(label);
		}
	}
}